#!/bin/bash

# check tcrypt images parsing

CRYPTSETUP=../src/cryptsetup
TST_DIR=tcrypt-images
MAP=tctst
PASSWORD="aaaaaaaaaaaa"
PASSWORD_HIDDEN="bbbbbbbbbbbb"

function remove_mapping()
{
	[ -b /dev/mapper/$MAP ] && dmsetup remove $MAP
	[ -b /dev/mapper/"$MAP"_1 ] && dmsetup remove "$MAP"_1
	[ -b /dev/mapper/"$MAP"_2 ] && dmsetup remove "$MAP"_2
}

function fail()
{
	[ -n "$1" ] && echo "$1"
	echo " [FAILED]"
	remove_mapping
	exit 2
}

function skip()
{
	[ -n "$1" ] && echo "$1"
	echo "Test skipped."
	exit 0
}

function test_one()
{
	$CRYPTSETUP benchmark -c "$1" -s "$2" | grep -v "#" || skip
}

function test_required()
{
	which lsblk >/dev/null 2>&1 || skip "WARNING: lsblk tool required."

	echo "REQUIRED KDF TEST"
	$CRYPTSETUP benchmark -h ripemd160 | grep "N/A" && skip
	$CRYPTSETUP benchmark -h whirlpool | grep "N/A" && skip

	echo "REQUIRED CIPHERS TEST"
	echo "#  Algorithm | Key |  Encryption |  Decryption"

	test_one aes-cbc 256
	test_one aes-lrw 384
	test_one aes-xts 512

	test_one twofish-cbc 256
	test_one twofish-lrw 384
	test_one twofish-xts 512

	test_one serpent-cbc 256
	test_one serpent-lrw 384
	test_one serpent-xts 512

	test_one blowfish-cbc 256

	test_one des3_ede-cbc 192
	test_one cast5 128
}

test_required
export LANG=C

[ ! -d $TST_DIR ] && tar xjf tcrypt-images.tar.bz2

echo "HEADER CHECK"
for file in $(ls $TST_DIR/tc_*) ; do
	echo -n " $file"
	echo $PASSWORD | $CRYPTSETUP tcryptDump $file >/dev/null || fail
	echo " [OK]"
done

echo "HEADER CHECK (HIDDEN)"
for file in $(ls $TST_DIR/tc_*-hidden) ; do
	echo -n " $file (hidden)"
	echo $PASSWORD_HIDDEN | $CRYPTSETUP tcryptDump --tcrypt-hidden $file >/dev/null || fail
	echo " [OK]"
done

echo "HEADER KEYFILES CHECK"
for file in $(ls $TST_DIR/tck_*) ; do
	echo -n " $file"
	echo $PASSWORD | $CRYPTSETUP tcryptDump -d $TST_DIR/keyfile1 -d $TST_DIR/keyfile2 $file >/dev/null || fail
	echo " [OK]"
done


if [ $(id -u) != 0 ]; then
	echo "WARNING: You must be root to run activation part of test, test skipped."
	exit 0
fi

echo "ACTIVATION FS UUID CHECK"
for file in $(ls $TST_DIR/tc_*) ; do
	echo -n " $file"
	out=$(echo $PASSWORD | $CRYPTSETUP tcryptOpen -r $file $MAP 2>/dev/null)
	[ $? -ne 0 ] && ( echo "$out" | grep -q -v "TCRYPT legacy mode" ) && echo " [N/A]" && continue
	$CRYPTSETUP status $MAP >/dev/null || fail
	$CRYPTSETUP status /dev/mapper/$MAP >/dev/null || fail
	UUID=$(lsblk -n -o UUID /dev/mapper/$MAP)
	$CRYPTSETUP remove $MAP || fail
	[ "$UUID" != "DEAD-BABE" ] && fail "UUID check failed."
	echo " [OK]"
done

echo "ACTIVATION FS UUID (HIDDEN) CHECK"
for file in $(ls $TST_DIR/tc_*-hidden) ; do
	echo -n " $file"
	out=$(echo $PASSWORD_HIDDEN | $CRYPTSETUP tcryptOpen -r $file $MAP --tcrypt-hidden 2>/dev/null)
	[ $? -ne 0 ] && ( echo "$out" | grep -q -v "TCRYPT legacy mode" ) && echo " [N/A]" && continue
	UUID=$(lsblk -n -o UUID /dev/mapper/$MAP)
	$CRYPTSETUP remove $MAP || fail
	[ "$UUID" != "CAFE-BABE" ] && fail "UUID check failed."
	echo " [OK]"
done
